package com.yitiao.data_algorithms.leetcode.editor.cn;

import com.yitiao.data_algorithms.leetcode.editor.cn.base.ListNode;
import com.yitiao.data_algorithms.leetcode.editor.cn.base.TreeNode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

class FindDuplicateSubtrees {
    // 2022-08-15 10:27:25
    //leetcode submit region begin(Prohibit modification and deletion)

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     * int val;
     * TreeNode left;
     * TreeNode right;
     * TreeNode() {}
     * TreeNode(int val) { this.val = val; }
     * TreeNode(int val, TreeNode left, TreeNode right) {
     * this.val = val;
     * this.left = left;
     * this.right = right;
     * }
     * }
     */
    class Solution {
        List<TreeNode> ans = new ArrayList<>();
        Map<String, Integer> count = new HashMap();

        public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
            dfs(root);
            return ans;
        }

        private String dfs(TreeNode root) {
            if (root == null) return "";
            String left = dfs(root.left);
            String right = dfs(root.right);
            String key = root.val + "," + left + "," + right;
            count.put(key, count.getOrDefault(key, 0) + 1);
            if (count.get(key) == 2) {
                ans.add(root);
            }
            return key;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}